﻿using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Three.Model;
using ThreeApi.Repositories;

namespace ThreeApi.Controllers
{
    /*
      ApiController Attribute 的作用: [ApiController]
      Attribute路由
      对Model自定验证
      推断源:[FromBody]、[FromForm]、[FromRoute]、[FromQuery]、[FromHeader],[FromServices]
      比如Controller标注了[ApiController]下面的:Add([FromBody]Department department)中的[FromBody]可以不写,可以自动推断源.
    */


    //MVC中继承Controller,该类中添加了对View的支持
    //WebAPI中推荐继承ControllerBase:没有View的支持
    //Controller继承于ControllerBase
    //restful api:主要通过http动词来区分这些action的
    [Route("v1/[controller]")]
    [ApiController]
    public class DepartmentsController : ControllerBase
    {
        private readonly IDepartmentRepository _departmentRepository;

        public DepartmentsController(IDepartmentRepository departmentRepository)
        {
            _departmentRepository = departmentRepository;
        }

        //路由路径:v1/Departments 
        //verb(动词):GET
        [HttpGet]
        public async Task<ActionResult<IEnumerable<Department>>> GetAll()
        {
            var departments = await _departmentRepository.GetAll();
            if (!departments.Any())
            {
                return NoContent();
            }

            //return Ok(departments);
            return new ObjectResult(departments);
        }

        //路由路径:v1/Departments 
        //verb(动词):POST
        [HttpPost]
        public async Task<ActionResult<Department>> Add([FromBody]Department department)
        {
            var added = await _departmentRepository.Add(department);

            return Ok(added);
        }

    }
}
